package com.chaihu.generator.backend;

import com.chaihu.generator.util.FileUtilBase;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 *
 */
public class GeneratorDtoBean extends BaseGenerator {


    /**
     * 拼装 查询数量
     *
     * @param data        数据
     * @param fileContext 文件内容
     * @return filContext 数据
     */
    private String dealVariableAndGetSet(Data data, String fileContext) {

        Map<String, String> params = data.getParams();

        String variable = "";

        Boolean hasFieldTypeDate = false;
        for (String key : params.keySet()) {
            if ("id".equals(key) || "statusCd".equals(key)
                    || "createBy".equals(key)|| "createTime".equals(key)
                    || "updateBy".equals(key)|| "updateTime".equals(key)) {
                continue;
            }
            String fieldType = params.get(key);
            if (StringUtils.equals("Date", fieldType)) {
                hasFieldTypeDate = true;
            }
            variable += "\tprivate " + fieldType +" " + key + ";\n";
        }

        if (hasFieldTypeDate) {
            fileContext = fileContext.replace("$imports$", "import java.util.Date;\n");
        } else {
            fileContext = fileContext.replace("$imports$", "");
        }

        fileContext = fileContext.replace("$beanVariable$", variable);

        return fileContext;
    }


    /**
     * 生成代码
     *
     * @param data 数据
     */
    public void generator(Data data) throws Exception {
        StringBuffer sb = readFile("backendTemplate/dto.txt");
        String fileContext = sb.toString();
        fileContext = fileContext
                .replace("@@moduleName@@",data.getModuleName())
                .replace("@@tableName@@",data.getTableName())
                .replace("Order", toUpperCaseFirstOne(data.getName()))
                .replace("描述", data.getDesc());

        fileContext = dealVariableAndGetSet(data, fileContext);
        String writePath = BaseGenerator.getClassPath()
                + "out/backend/dto/" + data.getModuleName() + "/" + toUpperCaseFirstOne(data.getName()) + "Dto.java";

        writeFile(writePath, fileContext);
        //复制生成的文件到对应分区目录下
        if (data.isAutoMove()) {
            String distPath = "chaihu-bean\\src\\main\\java\\com\\chaihu\\bean\\dto\\" + data.getModuleName() + "/" + toUpperCaseFirstOne(data.getName()) + "Dto.java";
//            System.out.println(distPath);
            FileUtilBase.copyfile(writePath, distPath);
        }
    }
}
